﻿using System;
using System.IO.Ports;
using System.Windows.Forms;

namespace RS232Simulation
{
    public partial class MainForm : Form
    {
        private SerialPort serialPort;

        public MainForm()
        {
            InitializeComponent();
            InitializeSerialPort();
            LoadAvailablePorts();
        }

        private void InitializeSerialPort()
        {
            serialPort = new SerialPort();
            serialPort.DataReceived += SerialPort_DataReceived;
        }

        private void LoadAvailablePorts()
        {
            string[] ports = SerialPort.GetPortNames();
            cmbPort.Items.AddRange(ports);
            if (ports.Length > 0)
            {
                cmbPort.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("未找到可用的串口。");
            }
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string receivedData = serialPort.ReadLine();
            string formattedReceivedData = $"[RECV {DateTime.Now:yyyy-MM-dd HH:mm:ss}] {receivedData}";
            Invoke(new Action(() => txtDisplay.AppendText(formattedReceivedData + Environment.NewLine)));
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            if (serialPort.IsOpen)
            {
                string message = txtSend.Text;
                string formattedMessage = $"[SENT {DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}";
                serialPort.WriteLine(formattedMessage);
                txtDisplay.AppendText(formattedMessage + Environment.NewLine);
            }
            else
            {
                MessageBox.Show("请先打开串口连接。");
            }
        }

        private void btnOpenPort_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort.PortName = cmbPort.SelectedItem.ToString();
                serialPort.BaudRate = 9600;
                serialPort.Open();
                MessageBox.Show("串口已打开。");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开串口: {ex.Message}");
            }
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (serialPort.IsOpen)
            {
                serialPort.Close();
            }
        }
    }
}
